import React, { Component } from 'react';
import { Dialog,Input, Button, Select ,Lable ,Form, Field, Feedback} from '@icedesign/base';
import IceContainer from '@icedesign/container';
import { enquireScreen } from 'enquire-js';
import axios from 'axios';
import {hashHistory} from 'react-router';
import RolesTree from '../RolesTree';
import './EditRoles.scss'
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';
import {WEB_URL} from '../../../../utils/Config'
import {GET,POST,PUT,DELETE} from '../../../../utils/public'

const FormItem = Form.Item;
const defaultValue = {
  keywords: '',
  type: 'post',
  content: '',
};

export default class EditRoles extends Component {
  static displayName = 'EditRoles';

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      visible: false,
      value: defaultValue,
      isMobile: false,
      type:null,  //窗口打开方式，add or edit
      code:null,  //触发打开窗口的节点的 code
      parentCode:null,  //触发打开窗口的节点的 parentCode
      nodeId:null,  //触发打开窗口的节点的 id
      name:'',//角色名
      comment:'',//角色备注
      companyDataSource:[],
      style:{
      },
      ids:[],
    }
    this.handleChildChange=this.handleChildChange.bind(this); //监听子组件变化
    this.addToSave = this.addToSave.bind(this);
    this.editToSave = this.editToSave.bind(this);
    
  }

  handleChildChange(ids){ //处理子函数传回来的state,改变自身的state
    if(ids){
        this.setState({ids});  
    }
  }

  componentDidMount() {
    this.enquireScreenRegister();
    //获取公司列表
    this.getCompanyList();
  }

  enquireScreenRegister = () => {
    const mediaCondition = 'only screen and (max-width: 720px)';

    enquireScreen((mobile) => {
      this.setState({
        isMobile: mobile,
      });
    }, mediaCondition);
  }

  showDialog=()=> {
    this.setState({ visible: true });
  }

  hideDialog=()=> {
    this.field.reset();
    this.setState({ name:'',comment:'',visible: false,companyId:'',ids:[],type:null});
  }

  getCompanyList = ()=>{
    GET('api/company?noPage=true')
      .then(res=>{
        if(!res){
          Feedback.toast.error('与服务器失去连接，稍后再试！')
          return;
        }else if(res.code==200 && res.success){
          console.log(res)
          let arr = [];
          res.data.map(item=>{
            arr.push({label:item.companyName,value:item.id})
          })
          this.setState({companyDataSource:arr})
        }
      })
  }
  
  onOpen =(record,type)=>{
    this.field.reset();
    this.setState({type})
    //当前节点的code,及窗口打开类型：添加 add 编辑 edit
    if(type == 'edit'){
      //编辑角色权限时
      let roleId = record.id;
      this.field.setValues({name:record.name,companyId:record.company.id,comment:record.comment})
      this.setState({roleId})
    }
    setTimeout(()=>{
      this.showDialog()
    },1000)
  }

  onClose = () => {
    this.setState({name:'',comment:''})
    this.setState({
      visible: false
    })
  }

  onOk = () => {
     //校验
     console.log(this.field.getValues(),this.state.ids)
     
     this.field.validate((errors, values) => {
      if(errors){
        console.log(errors, values);
        return ;
      }
      let data = {
        name:values.name,
        comment:values.comment,
        company:{
          id:values.companyId
        },
        permissions: this.state.ids
      }
       this.state.type ==='edit'? this.editToSave(data):this.addToSave(data);
    });
  }
 
  //添加角色保存
  addToSave=(data)=>{
    let url = 'api/roles';
    POST(url,data)
      .then(res=>{
        if(!res){
          Feedback.toast.error('与服务器失去连接，稍后再试！')
        }else if(res.code==200 && res.success){
          Feedback.toast.success('保存成功')
          this.hideDialog();
          this.props.onSaveChange(true)  
        }else if(res.code== 400){
          this.resolveError(res.errors)
        }else{
          Feedback.toast.error(`网络出错，${res.msg}`);
          return;
        }
      },error=>{
        Feedback.toast.error(`网络出错，${error}`)
        return;
      })
  }

  //编辑角色保存
  editToSave=(data)=>{
    let url = 'api/roles/'+this.state.roleId;
    //编辑时，若不改变name和comment值时，无法从field.getValues中获取
    PUT(url,data)
      .then(res=>{
        if(!res){
          Feedback.toast.error('与服务器失去连接，稍后再试！')
        }else if(res.code==200 && res.success){
          Feedback.toast.success('保存成功')
          this.hideDialog();
          this.props.onSaveChange(true)  
        }else if(res.code== 400){
          this.resolveError(res.errors)
        }else{
          Feedback.toast.error(`网络出错，${res.msg}`);
          return;
        }
      },error=>{
        Feedback.toast.error(`网络出错，${error}`)
        return;
      })
  }

  resolveError=errors=>{
    //异常处理
    errors.forEach((item)=>{
      const { getError, setError, setErrors } = this.field;
      let name = item.field;
      let msg = item.message;
      setError(name, msg);
    })
  }

  onCancel = () => {
    this.setState({
      visible: false
    })
  }

  onFormChange = (value) => {
    this.setState({
      value,
    });
  };

  render() {
    const { isMobile } = this.state;
    
    const EditRoles = {
      ...styles.EditRoles,
    };
    const formItemLayout = {
            labelCol: {
              fixedSpan: 10
            },
            wrapperCol: {
              span: 14
            }
          }
    const init = this.field.init;
  
    // 响应式处理
    if (isMobile) {
      EditRoles.width = '300px';
    }

    return (
        <Dialog
          className="edit-dialog"
          style={EditRoles}
          autoFocus={false}
          hasMask={false}
          title="角色管理"
          {...this.props}
          onOk={this.onOk}
          onCancel={this.hideDialog}
          onClose={this.hideDialog}
          visible={this.state.visible}>
        <Form direction="ver" field={this.field}>
            {/* <FormItem label=" " {...formItemLayout}>
              <Button type="primary" onClick={this.handleSubmit.bind(this)}>保存</Button>&emsp;
              <Button  onClick={this.onCancel}>取消</Button>
            </FormItem> */}

            <FormItem label="角色名" {...formItemLayout} >
              <Input placeholder="" required {...init("name",{ rules: [{ required: true,message: "不能为空" }]})}/>
            </FormItem >
            <FormItem label="所属公司" {...formItemLayout} >
              <Select placeholder="选择公司" dataSource={this.state.companyDataSource} style={{width:"100%"}} required {...init("companyId",{ rules: [{ required: true,message: "不能为空" },
                    ]})}/> 
            </FormItem >
            <FormItem label="权限" {...formItemLayout} >
                <RolesTree roleId={this.state.roleId} type={this.state.type}  onChange={this.handleChildChange} />
            </FormItem >
            <FormItem label="备注说明"  {...formItemLayout}>
              <Input multiple placeholder="" {...init("comment")} />
            </FormItem>
        </Form>
        </Dialog>
      
    );
  }
}

const styles = {
  EditRoles: { width: '640px'},
  input: { width: '100%' },

};
